package com.guoxiang.bigdata.paser.impl;

import com.guoxiang.bigdata.domain.TieZi;
import com.guoxiang.bigdata.paser.Parser;
import com.guoxiang.bigdata.scheduler.Scheduler;
import com.guoxiang.bigdata.scheduler.impl.BaiduTiebaSchedualForRedis;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;

/**
 * 解析html页面类
 */
public class BaidutiebaParse implements Parser {


    private HtmlCleaner htmlCleaner=new HtmlCleaner();
    private Scheduler scheduler= BaiduTiebaSchedualForRedis.getBdQueue();

    /**
     * 解析页面的href链接
     * @param html
     */
    @Override
    public void parsePageList(String html) {
        TagNode tagNode=htmlCleaner.clean(html);
        //System.out.println(html);
        //System.out.println(tagNode);
        try {
            Object[] objects = tagNode.evaluateXPath("//a[@class='j_th_tit ']/@href");
            if(objects.length==0){
                System.out.println("解析列表为空!");
            }

            for (Object object : objects) {
                //System.out.println(object);
                scheduler.push(object.toString());
            }
        } catch (XPatherException e) {
            System.out.println("bbb");
        }
    }

    /**
     * 解析具体页
     * @param html
     * @return
     */
    public TieZi parseCurrentToTiezi(String html){
        TagNode tagNode = htmlCleaner.clean(html);
       // System.out.println(html);
        TieZi tiezi=new TieZi();
        try {
            //所有发帖人
            Object[] objects1 = tagNode.evaluateXPath("//*[@id='j_p_postlist']/div[1]/div[1]/ul/li[3]/a/text()");
            if(objects1!=null&& objects1.length>0){
                String author = objects1[0].toString();
                tiezi.setAuthor(author);
            }

            //帖子的标题
            Object[] objects2 = tagNode.evaluateXPath("//h3[@class='core_title_txt pull-left text-overflow  ']/text()");
            if(objects2!=null&& objects2.length>0) {
                String title = objects2[0].toString();
                tiezi.setTitle(title);
            }
            //帖子的图片
            Object[] objects3 = tagNode.evaluateXPath("//img[@class='BDE_Image']/@src");
            for (Object imgurl : objects3) {
                tiezi.getImage().add(imgurl.toString());
            }
            //System.out.println(tiezi);
            return tiezi;

        } catch (XPatherException e) {
            e.printStackTrace();
        }
        return null;

    }
}
